import type { App } from 'vue';

/**
 * input 去除前后空格
 * @directive v-trim去除前后空格
 */

const getInput = (el) => {
    if (el.tagName === 'TEXTAREA') return el;
    return el.querySelector('textarea') || el.querySelector('input');
}

export function trimDirective(app: App) {
    app.directive('trim', {
        mounted(el, binding) {
            const input = getInput(el);
            if (!input) return;
            const trimFn = () => {
                const newVal = input.value.trim();
                if (input.value !== newVal) {
                    input.value = newVal;
                    input.dispatchEvent(new Event('input'));
                }
            };

            input.addEventListener('blur', trimFn);
            el._trimHandler = trimFn;
        },
        unmounted(el) {
            const input = getInput(el);
            if (input && el._trimHandler) {
                input.removeEventListener('blur', el._trimHandler);
            }
        }
    });
}
